/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sun.hunk.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 *
 * @author Administrator
 */
public class MathUtil {

    public static String getPercentageValue(int value, int percentage) {        
        double result = (new Double(value) * percentage) / 100;        
        return new Double(result).toString();
    }

    public static String getPercentageValueForExp(String value, String percentage) throws ScriptException {

        Pattern p = Pattern.compile("[\\d]+%");
        Matcher m = p.matcher(percentage);
        while (m.find()) {
            String matchedWord = m.group();         
            percentage = percentage.replace(matchedWord, getPercentageValue(Integer.parseInt(value), Integer.parseInt(matchedWord.replace("%", ""))));
        }
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        String expression = percentage;
        Object result = engine.eval(expression);        
        return new Double(result.toString()) + "";
    }

    public static String getPercentageValueForExpression(String value, String percentage) throws ScriptException {
        if(value == null){
            return percentage;
        }
        String result = "";
        boolean isFirst = true;
        for(String v : value.split("/")){         
            if(isFirst){
                result += getPercentageValueForExp(v, percentage);
                isFirst = false;
            }else{
                result += "/" + getPercentageValueForExp(v, percentage);
            }
        }
        return result;
    }

    public static void main(String[] args) throws ScriptException {
        String percentage = "500 + 45%";
        String value = "50";
        System.out.println("RESULT : " + getPercentageValueForExpression(value, percentage));

    }
}
